import React, { useState, useMemo, useCallback } from 'react';
import { DatePicker, TimePicker, Form, Card, Radio, List, notification } from 'antd';
import moment from 'moment';
import 'moment/locale/zh-cn';
import './index.less';

moment.locale('zh-cn');

const initialCourses = [
    {
        id: 1,
        name: '数学课',
        teacher: '王老师',
        date: moment().format('YYYY-MM-DD'),
        startTime: '08:00',
        endTime: '10:00'
    },
    {
        id: 2,
        name: '英语课',
        teacher: '李老师',
        date: moment().add(1, 'days').format('YYYY-MM-DD'),
        startTime: '14:00',
        endTime: '16:00'
    }
];

const ScheduleSystem = () => {
    const [viewMode, setViewMode] = useState('month');
    const [selectedMonth, setSelectedMonth] = useState(moment());
    const [dateRange, setDateRange] = useState([moment(), moment().add(7, 'days')]);
    const [timeRange, setTimeRange] = useState({
        start: moment().set({ hour: 8, minute: 0 }),
        end: moment().set({ hour: 20, minute: 0 })
    });
    const [selectedDate, setSelectedDate] = useState(moment());
    const [courses] = useState(initialCourses);

    // 生成日期列表
    const dateList = useMemo(() => {
        const start = viewMode === 'month'
            ? selectedMonth.clone().startOf('month')
            : dateRange[0].clone();
        const end = viewMode === 'month'
            ? selectedMonth.clone().endOf('month')
            : dateRange[1].clone();

        const dates = [];
        let current = start.clone();
        while (current.isSameOrBefore(end)) {
            dates.push(current.clone());
            current.add(1, 'day');
        }
        return dates;
    }, [viewMode, selectedMonth, dateRange]);

    // 生成周数据
    const weekData = useMemo(() => {
        const week = [];
        const start = selectedDate.clone().startOf('isoWeek');
        for (let i = 0; i < 7; i++) {
            week.push(start.clone().add(i, 'days'));
        }
        return week;
    }, [selectedDate]);

    // 生成时间轴
    const timeSlots = useMemo(() => {
        const slots = [];
        let current = timeRange.start.clone();
        while (current.isBefore(timeRange.end)) {
            slots.push(current.clone());
            current.add(1, 'hour');
        }
        return slots;
    }, [timeRange]);

    // 修复后的课程位置计算
    const calculateCoursePosition = useCallback((course) => {
        const courseDate = moment(course.date);
        const courseDayIndex = weekData.findIndex(d => d.isSame(courseDate, 'day'));
        if (courseDayIndex === -1) return { display: 'none' };

        // 时间计算修正
        const start = moment(course.startTime, 'HH:mm');
        const end = moment(course.endTime, 'HH:mm');

        // 相对于时间轴起始时间的位置
        const baseTime = timeRange.start.clone();
        const startDiff = start.diff(baseTime, 'minutes');
        const duration = end.diff(start, 'minutes');

        return {
            left: `${(courseDayIndex * 100) / 7}%`,
            top: `${startDiff + 60}px`,  // 每分钟1px
            height: `${duration}px`,
            width: `${100 / 9}%`,
            display: 'block',
            marginLeft: 90
        };
    }, [weekData, timeRange]);

    // 课程块组件
    const CourseBlock = ({ course }) => {
        const positionStyle = calculateCoursePosition(course);

        return (
            <div
                className="course-block"
                style={positionStyle}
            >
                <div className="course-time">
                    {course.startTime} - {course.endTime}
                </div>
                <div className="course-name">{course.name}</div>
                <div className="course-teacher">{course.teacher}</div>
            </div>
        );
    };

    // 日期选择样式
    const checkTimeStatus = (date) => {
        const isSelected = selectedDate.isSame(date, 'day');
        const isPast = date.isBefore(moment(), 'day');

        if (isSelected) return 'date-selector-color2';
        if (isPast) return 'date-selector-color1';
        return 'date-selector-color3';
    };

    return (
        <div className="schedule-system">
            <Card title="排课设置">
                {/* 控制面板 */}
                <Form layout="inline">
                    <Form.Item label="查看模式">
                        <Radio.Group
                            value={viewMode}
                            onChange={e => setViewMode(e.target.value)}
                            options={[
                                { label: '按月查看', value: 'month' },
                                { label: '按范围查看', value: 'range' }
                            ]}
                        />
                    </Form.Item>

                    {viewMode === 'month' ? (
                        <Form.Item label="选择月份">
                            <DatePicker.MonthPicker
                                value={selectedMonth}
                                disabledDate={current => current < moment().startOf('month')}
                                onChange={setSelectedMonth}
                                format="YYYY年MM月"
                            />
                        </Form.Item>
                    ) : (
                        <Form.Item label="日期范围">
                            <DatePicker.RangePicker
                                value={dateRange}
                                onChange={dates => setDateRange(dates || [moment(), moment().add(7, 'days')])}
                                disabledDate={current => current < moment().startOf('day')}
                            />
                        </Form.Item>
                    )}

                    <Form.Item label="每日时段">
                        <TimePicker.RangePicker
                            format="HH:mm"
                            value={[timeRange.start, timeRange.end]}
                            onChange={values => setTimeRange({
                                start: values?.[0] || moment().set({ hour: 8, minute: 0 }),
                                end: values?.[1] || moment().set({ hour: 20, minute: 0 })
                            })}
                        />
                    </Form.Item>
                </Form>

                {/* 日期选择列表 */}
                <div className="date-selector">
                    <List
                        grid={{ gutter: 16, column: 16 }}
                        dataSource={dateList}
                        renderItem={date => (
                            <List.Item>
                                <div
                                    className={`date-selector-box ${checkTimeStatus(date)}`}
                                    onClick={() => !date.isBefore(moment(), 'day') && setSelectedDate(date)}
                                >
                                    <div>{date.format('MM-DD')}</div>
                                    <div>{date.format('dddd')}</div>
                                </div>
                            </List.Item>
                        )}
                    />
                </div>

                {/* 课程表网格 */}
                <div className="schedule-grid">
                    {/* 课程块 */}
                    {courses.map(course => (
                        <CourseBlock key={course.id} course={course} />
                    ))}

                    {/* 网格表头 */}
                    <div className="grid-header">
                        <div className="time-column">
                            <div className="time-label">时间/日期</div>
                            {timeSlots.map((time, index) => (
                                <div style={{ height: 60 }} key={index} className="time-label">
                                    {time.format('HH:mm')}
                                </div>
                            ))}
                        </div>

                        {/* 日期列 */}
                        {weekData.map((date, dateIndex) => (
                            <div
                                key={dateIndex}
                                className="date-column"
                            >
                                <div className="date-header">
                                    {date.format('DD')} {date.format('dddd')}
                                </div>
                                {timeSlots.map((time, timeIndex) => (
                                    <div
                                        key={timeIndex}
                                        className="time-cell"
                                    >
                                        {/* 时间格子内容 */}
                                    </div>
                                ))}
                            </div>
                        ))}
                    </div>
                </div>
            </Card>
        </div>
    );
};

export default ScheduleSystem;